package com.wbl.train.gateway.filter;

import com.wbl.train.gateway.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Author: 王博纶
 * Date: 2024/1/26 13:53
 * FileName: LoginMemberFilter
 * Description: 会员登录信息的校验
 */
@Component
public class LoginMemberFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(LoginMemberFilter.class);
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 获取当前请求的路径
        String path = exchange.getRequest().getURI().getPath();
        log.info("authorFilter开始执行,当前路径为：{}",path);
        //排除不需要的请求
        if(path.contains("/admin")
                || path.contains("/hello")
                || path.contains("/member/member/login")
                || path.contains("/member/member/register")
                || path.contains("/member/member/sendCode")){
            log.info("{} 路径不需要进行登录验证",exchange.getRequest().getURI());
            // 继续往下执行
            return chain.filter(exchange);
        }

        log.info("路径开始登录验证：{}",exchange.getRequest().getURI());
        // 从请求头中获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        // 判断token是否为空
        if(token == null || "".equalsIgnoreCase(token)){
            log.info("token为空，请求被拦截");
            // 设置返回的状态码为：401 未认证 UNAUTHORIZED
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        // token是否失效
        if(!JwtUtil.validate(token)){
            log.info("token无效，请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        log.info("token有效，请求放行");
        return chain.filter(exchange);
    }

    /**
     * 设置过滤器的执行顺序 ， 从小到大执行
     * @return 执行的顺序
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
